package com.example.seakdreamandroid.sleepRecord;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.seakdreamandroid.Constant;
import com.example.seakdreamandroid.R;
import com.example.seakdreamandroid.entity.User;
import com.example.seakdreamandroid.sleep.entity.SleepInfo;
import com.example.seakdreamandroid.sleepRecord.SleepRecordAdapter;
import com.google.gson.JsonObject;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SNIHostName;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class RecordPerDay extends Fragment {
    private static final int LAYOUT_ID = R.layout.fragment_rpd;
    private static final String TAG = "RecordPerDay";
    private static final int OK = 1;
    private static final int ERROR = 2;
    private static final int REFRESH = 3;
    private static final int LOAD_MORE = 4;
    private RecyclerView rv;
    private SmartRefreshLayout sm;
    private SleepRecordAdapter adapter;
    private List<SleepInfo> records;
    private View v;
    private Activity activity;
    private User user;
    private int mPage = 1;
    Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch(msg.what){
                case OK:
                    adapter.notifyDataSetChanged();
                    if(msg.arg1 == REFRESH){
                        sm.finishRefresh();
                        adapter.notifyDataSetChanged();
                    }else{
                        sm.finishLoadMore();
                        adapter.notifyDataSetChanged();
                    }
                    break;
                case ERROR:
                    Log.e(TAG,"获取数据失败，网络故障");
                    if(msg.arg1 == REFRESH){
                        sm.finishRefresh();
                    }else{
                        sm.finishLoadMore();
                    }
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        v = inflater.inflate(LAYOUT_ID,container,false);
        activity = getActivity();
        user = (User) activity.getApplicationContext();
        initView();
        setListener();
        records = new ArrayList<SleepInfo>();
        adapter = new SleepRecordAdapter(records,activity);
        rv.setAdapter(adapter);
        getData(mPage,REFRESH);
        return v;
    }

    private void setListener() {
        sm.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPage = 1;
                records.clear();
                sm.setEnableLoadMore(true);
                getData(mPage,REFRESH);
            }
        });
        sm.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPage++;
                getData(mPage,LOAD_MORE);
            }
        });
    }

    private void initView() {
        sm = v.findViewById(R.id.sm);
        sm.setRefreshHeader(new ClassicsHeader(activity));
        sm.setRefreshFooter(new ClassicsFooter(activity));
        rv = v.findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(activity));
    }


    public void getData(int page,int type){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "sleep/findSleepInfoUsePage?userId="+user.getUserId() + "&page=" + mPage)
                .get()
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG,"分页请求睡眠记录失败");
                e.printStackTrace();
                Message msg = handler.obtainMessage();
                msg.what = ERROR;
                msg.arg1 = type;
                handler.sendMessage(msg);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String body = response.body().string();
                try {
                    JSONObject obj = new JSONObject(body);
                    if (obj.getString("data").equals("null")) {
                        Message msg = handler.obtainMessage();
                        msg.what=OK;
                        msg.arg1=type;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONArray array = obj.getJSONArray("data");
                    if(array.length()!=20){
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                sm.setEnableLoadMore(false);
                                Toast.makeText(activity,"没有更多了，去上面看看吧",Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                    for(int i = 0; i < array.length(); i++){
                        JSONObject temp = array.getJSONObject(i);
                        SleepInfo sleepInfo = new SleepInfo();
                        sleepInfo.setSleepId(temp.getString("sleepId"));
                        sleepInfo.setUserId(temp.getString("userId"));
                        sleepInfo.setAsleepTime(temp.getString("asleepTime"));
                        sleepInfo.setAwakeTime(temp.getString("awakeTime"));
                        records.add(sleepInfo);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Message msg = handler.obtainMessage();
                msg.what = OK;
                msg.arg1 = type;
                handler.sendMessage(msg);
            }
        });
    }
}
